﻿using IM.Easy.Core.Attributes;
using IM.Easy.Core.Filters;
using IM.Easy.Core.Utils;
using IM.Easy.CoreServices.IServices;
using IM.Easy.Entity.System;
using IM.Easy.Infrastructure.Constants;
using IM.Easy.Infrastructure.Query;
using IM.Easy.MsgServices.IServices;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.Dtos.Department;
using IM.Easy.SystemServices.Dtos.User;
using IM.Easy.SystemServices.IServices;
using IM.Easy.SystemServices.Services;
using Microsoft.AspNetCore.Mvc;

namespace IM.Easy.Api.Controllers.System
{
    [Route("system/user")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userServices;
        private readonly IDepartmentService _departmentService;
        private readonly IParamsService _paramsService;
        private readonly IEmailAccountService _emailAccountService;
        private readonly ISysAccountSecurityService _sysAccountSecurityService;

        public UserController(IUserService userServices, IDepartmentService departmentService, IParamsService paramsService, IEmailAccountService emailAccountService, ISysAccountSecurityService sysAccountSecurityService)
        {
            _userServices = userServices;
            _departmentService = departmentService;
            _paramsService = paramsService;
            _emailAccountService = emailAccountService;
            _sysAccountSecurityService = sysAccountSecurityService;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [Api(Name = "获取用户列表", Perm = "user:list")]
        public PageResponse<SysUser> GetList(UserQueryDto query)
        {
            var orgs = new List<long>();
            if (query.DeptId != default)
                orgs.Add(query.DeptId);
            if (query.LeafDept && query.DeptId != default)
            {
                var tmp = _departmentService.GetChildrens(new SysDepartmentTreeQueryDto { SelfId = query.DeptId, IncludeSelf = false });
                orgs.AddRange(tmp.Select(s => s.Id));
            }
            return query.DeptId == default ? _userServices.GetList(query, null) : _userServices.GetList(query, [.. orgs]);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        [Api(Name = "添加用户", Perm = "user:add")]
        [ServiceFilter(typeof(TransactionFilter))]
        public void Create([FromBody] UserCreateDto userDto)
        {
            userDto.CreationSource = "Manual"; //超管分配
            var user = _userServices.Create(userDto);
            //分配本地邮箱
            _emailAccountService.Create(new Entity.Msg.EmailAccount { UserId = user.Id, IsActive = user.LocalEmail, Account = $"{userDto.UserName}@im.com" });
            _sysAccountSecurityService.Create(new SysAccountSecurity { UserId = user.Id });

        }

        /// <summary>
        /// 获取基本用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        [Api(Name = "获取用户明细", Perm = "user:info")]
        public UserResponseDto Get([FromRoute] long id)
        {
            return _userServices.GetUser(id);
        }

        [HttpDelete("{id}")]
        [Api(Name = "删除用户", Perm = "user:del")]
        public bool Delete([FromRoute] long id)
        {
            var manageDepts = _departmentService.GetByManager(id);
            if (manageDepts != null && manageDepts.Count > 0)
                ExceptionUtils.ThrowBusinessException($"用户作为部门负责人无法删除：【{string.Join(',', manageDepts.Select(s => s.Name))}】");
            return _userServices.Delete(id);
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="userDto"></param>
        /// <returns></returns>
        [Api(Name = "更新用户", Perm = "user:put")]
        public bool Update([FromBody] UserCreateDto userDto)
        {
            var flag = _userServices.Update(userDto);
            var email = _emailAccountService.GetAccount(userDto.Id);
            if (email == null)
            {
                //分配本地邮箱
                _emailAccountService.Create(new Entity.Msg.EmailAccount { UserId = userDto.Id, IsActive = userDto.LocalEmail, Account = $"{userDto.UserName}@im.com" });
            }
            else
            {
                email.IsActive = userDto.LocalEmail;
                _emailAccountService.Update(email);
            }
            return flag;


        }

        /// <summary>
        /// 修改用户启用状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPut("active/{id}")]
        [Api(Name = "修改用户启用状态", Perm = "user:active")]
        public bool SetUserActiveStatus([FromRoute] long id, [FromQuery] bool status)
        {
            bool result = status ? _userServices.Enable(id) : _userServices.Disable(id);
            return result;
        }

        /// <summary>
        /// 初始化密码--重置密码
        /// </summary>
        /// <returns></returns>
        [HttpPut("initpwd/{userId}")]
        [Api(Name = "重置密码", Perm = "user:init:password")]
        public string InitialPassword(long userId)
        {
            var user = _userServices.GetById(userId);
            var password = _paramsService.GetValue(ParamsConstant.InitPassword);
            if (string.IsNullOrWhiteSpace(password)) ExceptionUtils.ThrowBusinessException($"系统参数:{ParamsConstant.InitPassword}，配置异常");
            var flag = _userServices.InitPassword(user.Id, password);
            return password;
        }

        /// <summary>
        /// 接触锁定状态
        /// </summary>
        [HttpPut("unlock/{userId}")]
        [Api(Name = "账号解锁", Perm = "user:unlock")]
        public bool UnLock(long userId)
        {
            var flag = _sysAccountSecurityService.UnLock(userId);
            return flag;
        }
    }
}
